<template>
  <a-table
    :data-source="dataSource"
    :columns="columns"
    row-key="name"
    expandRowByClick
    :expanded-row-keys="expandedRowKeys"
    @expandedRowsChange="onExpandedRowsChange"
    @expand="handleExpand"
  >
    <div
      slot="filterDropdown"
      slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
      style="padding: 8px"
    >
      <a-input
        v-ant-ref="(c) => (searchInput = c)"
        :placeholder="`请输入 ${column.dataIndex}搜索`"
        :value="selectedKeys[0]"
        style="width: 188px; margin-bottom: 8px; display: block"
        @change="(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])"
        @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
      />
      <a-button
        type="primary"
        icon="search"
        size="small"
        style="width: 90px; margin-right: 8px"
        @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
      >
        搜索
      </a-button>
      <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)"> 重置 </a-button>
    </div>
    <a-icon
      slot="filterIcon"
      slot-scope="filtered"
      type="search"
      :style="{ color: filtered ? '#108ee9' : undefined }"
    />
    <template slot="customRender" slot-scope="text, record, index, column">
      <span v-if="searchText && searchedColumn === column.dataIndex">
        <template
          v-for="(fragment, i) in text.toString().split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
        >
          <mark v-if="fragment.toLowerCase() === searchText.toLowerCase()" :key="i" class="highlight">{{
            fragment
          }}</mark>
          <template v-else>{{ fragment }}</template>
        </template>
      </span>
      <template v-else>
        <a-tooltip :title="text">
          <template #content>
            <div>{{ text }}</div>
          </template>
          <span>{{ text }}</span>
        </a-tooltip>
      </template>
    </template>
    <template slot="editName" slot-scope="text, record">
      <editable-cell :text="text" @change="onCellChange(record.key, 'dName', $event)" />
    </template>
    <template slot="expandedRowRender" slot-scope="record">
      <div v-if="loadingRows.includes(record.name)" style="text-align: center; padding: 20px">
        <a-spin size="small" /> 加载中...
      </div>
      <a-table
        v-else-if="record.variableDetailList && record.variableDetailList.length"
        :columns="innerColumns"
        :data-source="record.variableDetailList"
        :pagination="false"
        row-key="label"
        size="small"
      >
        <template slot="editRange" slot-scope="text, detail">
          <editable-cell
            :text="text"
            :showEdit="detail.binning_type === 'range'"
            @change="onDetailCellChange(record, detail.label, 'range', $event)"
          />
        </template>
        <template slot="editScore" slot-scope="text, detail">
          <editable-cell :text="text" @change="onDetailCellChange(record, detail.label, 'score', $event)" />
        </template>
      </a-table>
      <div v-else style="text-align: center; padding: 20px; color: #999">暂无数据</div>
    </template>
  </a-table>
</template>

<script>
import EditableCell from './EditableCell'
import { getScoreCardVariableDetail, setBinningDetail } from '@/api/scorecard'

export default {
  name: 'SearchTable',
  props: {
    currentDetailRecord: {
      type: Object,
      default: () => {},
    },
    dataSource: {
      type: Array,
      default: () => [],
    },
    output: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    EditableCell,
  },
  data() {
    return {
      searchText: '',
      searchInput: null,
      searchedColumn: '',
      columns: [
        {
          title: '变量名',
          dataIndex: 'name',
          key: 'name',
          ellipsis: true,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) => record.name.toString().toLowerCase().includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus()
              }, 0)
            }
          },
        },
        {
          title: '变量字段',
          dataIndex: 'type',
          key: 'type',
        },
        {
          title: '显示名',
          dataIndex: 'dName',
          key: 'dName',
          scopedSlots: {
            customRender: 'editName',
          },
        },
      ],
      innerData: [],
      innerColumns: [
        {
          title: '标签',
          dataIndex: 'label',
          key: 'label',
        },
        {
          title: '数值区间',
          dataIndex: 'range',
          key: 'range',
          scopedSlots: {
            customRender: 'editRange',
          },
        },
        {
          title: '分值',
          dataIndex: 'score',
          key: 'score',
          scopedSlots: {
            customRender: 'editScore',
          },
        },
      ],
      expandedRowKeys: [],
      loadingRows: [], // 新增：记录正在加载的行
      loadedRows: [], // 新增：记录已加载过数据的行
    }
  },
  methods: {
    handleSearch(selectedKeys, confirm, dataIndex) {
      confirm()
      this.searchText = selectedKeys[0]
      this.searchedColumn = dataIndex
    },

    handleReset(clearFilters) {
      clearFilters()
      this.searchText = ''
    },
    onCellChange(key, dataIndex, value) {
      const dataSource = [...this.dataSource]
      const target = dataSource.find((item) => item.key === key)
      if (target) {
        target[dataIndex] = value
        this.$emit('update:dataSource', dataSource)
      }
    },
    onDetailCellChange(record, label, dataIndex, value) {
      console.log(label, dataIndex, value)
      const { name, variableDetailList } = record
      const detail = [...variableDetailList]
      const target = detail.find((item) => item.label === label)
      if (target) {
        target[dataIndex] = value
      }
      setBinningDetail({
        binningDetail: JSON.stringify(detail),
        modelUuid: this.currentDetailRecord.uuid,
        variableName: name,
        version: this.currentDetailRecord.version,
      }).then((res) => {
        if (res.code === 200) {
          this.$message.success(res.message)
          // 刷新当前行数据
          this.loadDetail(record)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    onExpandedRowsChange(expandedRowKeys) {
      this.expandedRowKeys = expandedRowKeys
    },
    handleExpand(expanded, record) {
      if (expanded) {
        // 如果已经加载过数据，直接返回
        if (this.loadedRows.includes(record.name)) {
          return
        }
        // 加载数据
        this.loadDetail(record)
        // 添加到加载状态
        this.loadingRows.push(record.name)
      }
    },
    loadDetail(record) {
      getScoreCardVariableDetail({
        modelUuid: this.currentDetailRecord.uuid,
        version: this.currentDetailRecord.version,
        variableName: record.name,
      })
        .then((res) => {
          if (res.code === 200) {
            // 使用 Vue.set 确保响应式更新
            this.$set(record, 'variableDetailList', res.data || [])
            // 标记为已加载
            this.loadedRows.push(record.name)
          }
        })
        .catch((error) => {
          console.error('加载子表格数据失败:', error)
          // 设置空数组避免显示问题
          this.$set(record, 'variableDetailList', [])
        })
        .finally(() => {
          // 移除加载状态
          const index = this.loadingRows.indexOf(record.name)
          if (index > -1) {
            this.loadingRows.splice(index, 1)
          }
        })
    },
    // 新增：重置加载状态的方法
    resetLoadedState() {
      this.loadedRows = []
      this.loadingRows = []
    },
  },
}
</script>
<style scoped lang="less">
/* 确保搜索图标颜色为主题色 */
.ant-table-thead > tr > th .anticon-filter, .ant-table-thead > tr > th .ant-table-filter-icon {
  color: @primary-color !important;
}
</style>
